<template>
	<view class="container">
		<view class="top">
			<navigator url="/pages/index/index" open-type="switchTab">
				<image class="back" src="/static/images/白色左箭头.png"></image>
			</navigator>
			<view class="title">车辆保养</view>
		</view>

		<view class="map-container">
			<map class="map" :markers="markers" :include-points="include" :latitude="latitude" :longitude="longitude"
				@markertap="handleMarkerTap" @tap="closeMerchantPopup" :scale="mapScale"></map>
		</view>

		<cover-view class="popup" v-if="showMerchantPopup">
			<cover-view class="popup-content">
				<view>
					<view class="shopName">{{ currentMerchant.name }}</view>
					<view class="rate-container">
						<uni-rate :size="16" :value="currentMerchant.rate" :readonly="true" />
						<text class="rate-text">评分：{{ currentMerchant.rate }}分</text>
					</view>
					<view class="info-item">
						<text class="info-label">营业时间：</text>
						<text>{{ currentMerchant.startTime }} ~ {{ currentMerchant.endTime }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">位置：</text>
						<text>{{ currentMerchant.address }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">距离您：</text>
						<text>{{ currentMerchant.distance }}</text>
					</view>
				</view>
				<cover-image :src="currentMerchant.image || '/static/images/头像.jpg'" class="shopImg"></cover-image>
			</cover-view>
			<view class="btnView">
				<u-button type="primary" shape="circle" text="联系门店" icon="phone" @click="showPhonePopup = true" />
				<u-button type="primary" color="#ff6128" shape="circle" text="立即预订" icon="plus" @click="goToBooking" />
			</view>
		</cover-view>
		<view v-if="showPhonePopup" class="overlay">
			<view class="modal">
				<view class="title1">联系门店</view>
				<view class="content">电话：{{ phoneNumber }}</view>
				<view class="button">
					<button class="copy" @click="copyPhone">复制</button>
					<button class="cancel" @click="showPhonePopup = false">取消</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import request from '../../../uitls/request';
	export default {
		data() {
			return {
				showPhonePopup: false,
				showMerchantPopup: false,
				phoneNumber: '18642589456',
				latitude: '',
				longitude: '',
				markers: [],
				include: [],
				mapScale: 14,
				currentMerchant: null,

				merchantList: [{
						id: 3,
						name: '雷碧',
						operatingArea: '宁夏',
						startTime: '08:00',
						endTime: '20:00',
						address: '河南省郑州市荥阳市桃贾路',
						longitude: '113.463501',
						latitude: '34.734616',
						rate: 2,
						image: '',
					}
				]
			};
		},
		methods: {
			closePhonePopup() {
				this.showPhonePopup = false;
			},
			copyPhone() {
				uni.setClipboardData({
					data: '18642589456',
					success: () => {
						uni.showToast({
							title: '已复制',
							icon: 'success'
						});
					}
				});
			},
			closeMerchantPopup() {
				this.showMerchantPopup = false;
				this.currentMerchant = null;
				this.showPhonePopup = false;
				this.mapScale = 14;
			},
			getLocation() {
				uni.getLocation({
					success: (res) => {
						this.latitude = res.latitude;
						this.longitude = res.longitude;

						const merchantMarkers = this.merchantList.map(item => ({
							id: item.id,
							latitude: Number(item.latitude),
							longitude: Number(item.longitude),
							iconPath: '/static/mplocation.png',
							width: 30,
							height: 30
						}));

						const userMarker = {
							id: 999,
							latitude: res.latitude,
							longitude: res.longitude,
							iconPath: '/static/mplocation.png',
							width: 30,
							height: 30,
							callout: {
								content: '您的位置',
								color: '#e93d0d',
								fontSize: 15,
								display: 'ALWAYS',
								borderRadius: 20
							}
						};
						this.markers = [userMarker, ...merchantMarkers];
						this.include = this.markers;
					}
				});
			},
			handleMarkerTap(e) {
				const id = e.detail.markerId;
				if (id === 999) {
					this.closeMerchantPopup();
					return;
				}
				const merchant = this.merchantList.find(m => m.id === id);
				if (merchant) {
					// 计算距离
					const distanceInMeters = this.getDistance(
						this.latitude,
						this.longitude,
						Number(merchant.latitude),
						Number(merchant.longitude)
					);

					// 格式化为公里/米显示
					let displayDistance = '';
					if (distanceInMeters >= 1000) {
						displayDistance = (distanceInMeters / 1000).toFixed(2) + ' km';
					} else {
						displayDistance = Math.round(distanceInMeters) + ' m';
					}
					this.latitude = Number(merchant.latitude);
					this.longitude = Number(merchant.longitude);
					this.mapScale = 20;
					this.currentMerchant = {
						...merchant,
						distance: displayDistance
					};
					this.showMerchantPopup = true;
				}
			},
			getDistance(lat1, lon1, lat2, lon2) {
				const toRad = d => d * Math.PI / 180;
				const R = 6371e3; // 地球半径（单位：米）

				const φ1 = toRad(lat1);
				const φ2 = toRad(lat2);
				const Δφ = toRad(lat2 - lat1);
				const Δλ = toRad(lon2 - lon1);

				const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
					Math.cos(φ1) * Math.cos(φ2) *
					Math.sin(Δλ / 2) * Math.sin(Δλ / 2);

				const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

				const d = R * c;
				return d; // 单位：米
			},
			goToBooking() {
				if (this.currentMerchant) {
					uni.navigateTo({
						url: `/pages/zwj/baoyangxiangqing/baoyangxiangqing?id=${this.currentMerchant.id}`
					});
				}
			},
			getMerchantImage() {
				request({
					url: '/merchant/imgs/' + this.merchantList[0].id,
					method: 'GET',
					success: (res) => {
						console.log(res)
						this.merchantList[0].image = res.data.data[0].img
					}
				})
			}
		},
		onLoad() {
			this.getLocation();
			this.getMerchantImage();
		}
	};
</script>

<style scoped>
	.container {
		position: relative;
		padding-top: 20rpx;
		background-image: url("/static/组 8.png");
		background-size: 100% 40%;
		background-repeat: no-repeat;
		height: 100vh;
		display: flex;
		flex-direction: column;
		padding-bottom: 0;
	}

	.top {
		position: relative;
		z-index: 10;
		background: transparent;
	}

	.back {
		position: absolute;
		top: 30rpx;
		left: 20rpx;
		width: 32rpx;
		height: 32rpx;
		z-index: 2;
	}

	.title {
		text-align: center;
		font-size: 36rpx;
		color: #fff;
		line-height: 90rpx;
		font-weight: bold;
	}

	.map-container {
		flex: 1;
		width: 100%;
		position: relative;
	}

	.map {
		position: absolute;
		width: 100%;
		height: 100%;
	}

	.popup {
		position: absolute;
		bottom: 60rpx;
		left: 50%;
		transform: translateX(-50%);
		width: 90%;
		background-color: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.2);
		z-index: 99;
	}

	.popup-content {
		display: flex;
	}

	.shopName {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
		color: #333;
	}

	.rate-container {
		display: flex;
		align-items: center;
		margin-bottom: 15rpx;
	}

	.rate-text {
		margin-left: 15rpx;
		font-size: 26rpx;
		color: #666;
	}

	.info-item {
		margin-bottom: 12rpx;
		font-size: 28rpx;
		color: #666;
		line-height: 1.6;
	}

	.info-label {
		color: #333;
		font-weight: 500;
	}

	.distance {
		margin-top: 20rpx;
		font-size: 24rpx;
		color: #999;
	}

	.shopImg {
		width: 300rpx;
		height: 250rpx;
		margin-top: 10rpx;
		margin-left: 50rpx;
		border-radius: 10rpx;
	}

	.btnView {
		display: flex;
		justify-content: space-between;
		margin-top: 40rpx;
	}

	.btnView>button,
	.btnView>navigator {
		width: 48%;
	}

	.overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		z-index: 9999;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.title1 {
		font-size: 40rpx;
		font-weight: bold;
		color: black;
		margin-bottom: 10rpx;
	}

	.content {
		font-size: 30rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
	}

	.modal {
		width: 600rpx;
		background: white;
		border-radius: 20rpx;
		padding: 20rpx 40rpx;
		text-align: center;
	}

	.button {
		display: flex;
	}

	.copy {
		background-color: greenyellow;
		width: 170rpx;
		height: 80rpx;
		border: 1rpx solid black;
	}

	.cancel {
		border: 1rpx solid black;
		width: 170rpx;
		height: 80rpx;
	}
</style>